package com.bw.controller;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.Digester;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.domain.User;
import com.bw.service.UserService;
import com.bw.utils.common.JWTUtils;
import com.bw.utils.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.security.PublicKey;

@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    UserService userService;
    @Resource
    AuthenticationManager authenticationManager;
    @RequestMapping("/login")
    public Result login(@RequestBody User user){
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUname(),user.getPwd()+salt);
        authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        //以上不报错登录成功

//        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        userLambdaQueryWrapper.eq(User::getUname,user.getUname());
//        User one = userService.getOne(userLambdaQueryWrapper);
//        if(one==null){
//            return Result.fail("用户名不存在");
//        }
//        //用户输入密码加盐加密
//        String s = DigestUtil.md5Hex(user.getPwd() + salt);
//        if(!one.getPwd().equals(s)){
//            return Result.fail("密码不存在");
//        }
//        String token = JWTUtils.createToken(one.getId() + "", 12 * 60);
//        System.out.println("-------------------------"+token);
        String token = JWTUtils.createToken(user.getUname(), 12 * 60);
        return Result.success(token);

    }

    public static final String salt="nihao";
    @Resource
    PasswordEncoder passwordEncoder;
    @PostConstruct
    public String  initpwd(){
        String str="123";
//        String s = DigestUtil.md5Hex(str + salt);
        String encode = passwordEncoder.encode(str + salt);
        System.out.println("----------------------------"+encode);
        return encode;
    }
}
